/**
 * yiqihao(一起好商务股份有限公司) copyright 
 */
package com.p2p.backend.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import com.p2p.backend.service.BackWithdrawService;
import com.p2p.backend.service.ExportService;
import com.p2p.backend.service.P2PRechargeService;
import com.p2p.base.model.Money;
import com.p2p.base.page.PageVo;
import com.p2p.base.util.biz.ExcelUtil;
import com.p2p.base.util.biz.ModelViewUtil;
import com.p2p.front.dal.model.MemberPoint;
import com.p2p.front.dal.model.User;
import com.p2p.front.dal.model.UserCredits;
import com.p2p.front.service.MemberPointService;
import com.p2p.front.service.TenderAmountSumService;
import com.p2p.front.service.UserService;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.model.AccountVO;
import com.p2p.trans.client.result.AccountQueryResult;

/**
 *
 * @author leiruiqi@yiqihao.com
 *
 *         2015年4月2日 下午12:00:39
 */
@Service("exportService")
public class ExportServiceImpl implements ExportService {

	@Resource
	private P2PRechargeService p2PRechargeService;
	
	@Resource
	private BackWithdrawService withdrawService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private AccountQueryFacade remoteAccountQueryFacade;
	
	@Resource
	private MemberPointService memberPointService;
	
	@Resource
	private TenderAmountSumService tenderAmountSumService;
	
	@Override
	public void exportSucceseRecharge(OutputStream os,PageVo form) {
		// 创建工作薄
		HSSFWorkbook workBook = null;
		String[] cellTitle = { "流水号", "用户id号","手机","姓名", "真实姓名", "金额", "创建时间","支付时间","状态","管理员备注" };
		try {
			workBook = new HSSFWorkbook();// 创建工作薄
			HSSFSheet sheet = workBook.createSheet();
			workBook.setSheetName(0, "宝付充值记录");// 工作簿名称
			HSSFFont font = workBook.createFont();
			font.setColor(HSSFFont.COLOR_NORMAL);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			HSSFCellStyle cellStyle = workBook.createCellStyle();// 创建格式
			cellStyle.setFont(font);
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 创建第一行标题
			HSSFRow titleRow = sheet.createRow((short) 0);// 第一行标题
			for (int i = 0, size = cellTitle.length; i < size; i++) {// 创建第1行标题单元格
				
				HSSFCell cell = titleRow.createCell(i, 0);
				cell.setCellStyle(cellStyle);
				cell.setCellValue(cellTitle[i]);
			}
			List<String> nameList = new ArrayList<String>();
			nameList.add("id");
			nameList.add("uid");
			nameList.add("money");
			nameList.add("addTime");
			nameList.add("okTime");
			nameList.add("status");
			nameList.add("aremark");
			
			
			List<String> viewnameList = new ArrayList<String>();
			viewnameList.add("id");
			viewnameList.add("uid");
			viewnameList.add("umobile");
			viewnameList.add("uname");
			viewnameList.add("realname");
			viewnameList.add("money");
			viewnameList.add("addTime");
			viewnameList.add("okTime");
			viewnameList.add("status");
			viewnameList.add("aremark");
			
			
			form.setPageSize(100);
			form.setPageNum(1);
		
			PageVo result = p2PRechargeService.listPageForResultMap(form);
			this.filldRechargeShell(result, nameList, viewnameList, sheet);
			int page = result.getPages();
			for(int i=2;i<=page;i++){
				form.setPageNum(i);
				result = p2PRechargeService.listPageForResultMap(form);
				this.filldRechargeShell(result, nameList, viewnameList, sheet);
			}
			
			// 通过文件输出流生成Excel文件
			

			workBook.write(os);
			os.flush();
			os.close();
			//System.out.println("Excel 2003文件导出完成！导出文件路径：" + file.getPath());
		} catch (IOException e) {
			System.out.println("生成人员信息Excel发生IO 异常！" + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("文件导出发生异常！异常原因：" + e.getMessage());
			e.printStackTrace();
		}
	}

	
	private void filldRechargeShell(PageVo result,List<String> nameList,List<String> viewnameList,HSSFSheet sheet){
		int startrow =(result.getPageNum()-1)*result.getPageSize()+1;
		//List<>
		List<Map<String,Object>> rows = ModelViewUtil.getMapModelObjectList(result.getList(), nameList);
		List<String> uidList = new ArrayList<String>();
		for (Map<String, Object> oneRow : rows) {
			uidList.add(oneRow.get("uid").toString());
		}
		Map<String, User> userMap = userService.searchUserByIdList(uidList);
		for (Map<String, Object> oneRow : rows) {
			String uid = oneRow.get("uid").toString();
			User user = userMap.get(uid);
			if (user != null) {
				oneRow.put("umobile", user.getUmobile());
				oneRow.put("uname", user.getUname());
				oneRow.put("realname", user.getRealname());
			}
			Long addtime = (Long)oneRow.get("addTime");
			oneRow.put("addTime", new Date(addtime));
			
			Long endtime = (Long)oneRow.get("okTime");
			oneRow.put("okTime", new Date(endtime));
			
			Integer status = (Integer)oneRow.get("status");
			String strStatus = "未知";
			if(status == 1){
	     		  strStatus="失败";
	     	  }else if(status == 2){
	     		  strStatus="无效";
	     	  }else if(status ==11){
	     		  strStatus="充值中";
	     	  }else if(status ==12){
	     		  strStatus="待确认";
	     	  }else if(status ==21){
	     		  strStatus="充值成功";
	     	  }
			
			oneRow.put("status", strStatus);
		}
		ExcelUtil.filldExcelByNameList(rows, viewnameList, sheet,startrow);
	}
	
	private void filldWithdrawShell(PageVo result,List<String> viewnameList,HSSFSheet sheet){
		int startrow =(result.getPageNum()-1)*result.getPageSize()+1;
		List<Map<String,Object>> rows = (List<Map<String,Object>>)result.getList();
		for(Map<String,Object> row:rows){
			Integer status = (Integer)row.get("status");
			String statusName = null;
			switch(status){
			//1-失败,2-无效,11-等待处理,21-提现处理中,31-提现成功
			case 1:
				statusName="失败";
				break;
			case 2:
				statusName="无效";
				break;
			case 11:
				statusName="等待处理";
				break;
			case 21:
				statusName="提现处理中";
				break;
			case 31:
				statusName="提现成功";
				break;
			
			default :statusName="未知";
				break;
				
			}
			row.put("status", statusName);
			
			Long addtime = Long.valueOf(row.get("addtime").toString());
			row.put("addtime", new Date(addtime));
			
			Long money = Long.valueOf(row.get("money").toString());
			
			row.put("money", new Money(money));
			
		}
		ExcelUtil.filldExcelByNameList(rows, viewnameList, sheet,startrow);
	}

	@Override
	public void exportSucceseWithdraw(OutputStream os, PageVo form) {
		// 创建工作薄
				HSSFWorkbook workBook = null;
				//String[] cellTitle = { "流水号", "用户id号","金额","手续费", "申请时间", "姓名", "银行","省","市","分行","银行卡号","状态" };
				String[] cellTitle = {"提现流水号","用户ID","状态","提现金额","收费提现金额","提现费用","服务费"," 提现所花积分","开户名","开户银行","银行标识码","开户地区","开户城市","支行名称","银行账号","创建时间"};
				try {
					workBook = new HSSFWorkbook();// 创建工作薄
					HSSFSheet sheet = workBook.createSheet();
					workBook.setSheetName(0, "提现申请记录");// 工作簿名称
					HSSFFont font = workBook.createFont();
					font.setColor(HSSFFont.COLOR_NORMAL);
					font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
					HSSFCellStyle cellStyle = workBook.createCellStyle();// 创建格式
					cellStyle.setFont(font);
					cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
					// 创建第一行标题
					HSSFRow titleRow = sheet.createRow((short) 0);// 第一行标题
					for (int i = 0, size = cellTitle.length; i < size; i++) {// 创建第1行标题单元格
						
						HSSFCell cell = titleRow.createCell(i, 0);
						cell.setCellStyle(cellStyle);
						cell.setCellValue(cellTitle[i]);
					}
					
					List<String> viewnameList = new ArrayList<String>();
					viewnameList.add("id"); //提现ID
					viewnameList.add("uid"); //用户ID

					viewnameList.add("status"); //状态:1-失败,2-无效,11-等待处理,21-提现处理中,31-提现成功

					viewnameList.add("money"); //提现金额
					viewnameList.add("feedraw"); //收费提现金额
					viewnameList.add("fee"); //提现费用
					viewnameList.add("sfee"); //服务费
					viewnameList.add("score"); // 提现所花积分
					viewnameList.add("name"); //开户名
					viewnameList.add("bank"); //开户银行
					viewnameList.add("code"); //银行标识码
					viewnameList.add("area"); //开户地区
					viewnameList.add("city"); //开户城市
					viewnameList.add("branch"); //支行名称
					viewnameList.add("card"); //银行账号
					viewnameList.add("addtime"); //创建时间

					
					
					
					form.setPageSize(100);
					form.setPageNum(1);
				
					PageVo result = this.withdrawService.listPage(form);
					this.filldWithdrawShell(result, viewnameList, sheet);
					int page = result.getPages();
					for(int i=2;i<=page;i++){
						form.setPageNum(i);
						result = this.withdrawService.listPage(form);
						this.filldWithdrawShell(result,viewnameList, sheet);
					}
					
					// 通过文件输出流生成Excel文件
					

					workBook.write(os);
					os.flush();
					os.close();
					//System.out.println("Excel 2003文件导出完成！导出文件路径：" + file.getPath());
				} catch (IOException e) {
					System.out.println("生成人员信息Excel发生IO 异常！" + e.getMessage());
					e.printStackTrace();
				} catch (Exception e) {
					System.out.println("文件导出发生异常！异常原因：" + e.getMessage());
					e.printStackTrace();
				}
		
	}

	public static void main(String[] args) {
		
		String str = "id#提现ID;uid#用户ID;aid#管理ID;status#状态:1-失败,2-无效,11-等待处理,21-提现处理中,31-提现成功;method#0-普通提现,1-汇付提现,2-预约提现;money#提现金额;feedraw#收费提现金额;fee#提现费用;sfee#服务费;score# 提现所花积分;name#开户名;bank#开户银行;code#银行标识码;area#开户地区;city#开户城市;branch#支行名称;card#银行账号;addtime#创建时间;oktime#成功时间;uptime#更新时间;addip#创建IP;upip#更新IP;remark#备注;aremark#管理员备注";
		String[] array = str.split(";");
		StringBuilder sb = new StringBuilder();
		for(String tempStr:array){
			String[] tempArray = tempStr.split("#");
			System.out.println("viewnameList.add(\""+tempArray[0]+"\"); //"+tempArray[1]);
			sb.append("\""+tempArray[1]+"\",");
		}
		sb.deleteCharAt(sb.length()-1);
		System.out.println(sb.toString());
	}
	
	public void exportAllUser(OutputStream os, PageVo form) {
		
	
		// 创建工作薄
		HSSFWorkbook workBook = null;
		//String[] cellTitle = { "流水号", "用户id号","金额","手续费", "申请时间", "姓名", "银行","省","市","分行","银行卡号","状态" };
		String[] cellTitle = {"用户ID","用户名","真实姓名","电话","邮箱","资金账号","余额"," 总投资额","冻结额","可用余额","累计积分","可用积分","会员等级"};
		try {
			workBook = new HSSFWorkbook();// 创建工作薄
			HSSFSheet sheet = workBook.createSheet();
			workBook.setSheetName(0, "提现申请记录");// 工作簿名称
			HSSFFont font = workBook.createFont();
			font.setColor(HSSFFont.COLOR_NORMAL);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			HSSFCellStyle cellStyle = workBook.createCellStyle();// 创建格式
			cellStyle.setFont(font);
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 创建第一行标题
			HSSFRow titleRow = sheet.createRow((short) 0);// 第一行标题
			for (int i = 0, size = cellTitle.length; i < size; i++) {// 创建第1行标题单元格
				
				HSSFCell cell = titleRow.createCell(i, 0);
				cell.setCellStyle(cellStyle);
				cell.setCellValue(cellTitle[i]);
			}
			
			
			
			List<String> viewnameList = new ArrayList<String>();
			
			viewnameList.add("uid");
			viewnameList.add("uname");
			viewnameList.add("realname");
			viewnameList.add("umobile");
			viewnameList.add("uemail");
			viewnameList.add("accountNo");
			viewnameList.add("balance");
			viewnameList.add("totalTenderAmount");
			viewnameList.add("freeze");
			viewnameList.add("canUseBalance");
			viewnameList.add("produceCumulative");
			viewnameList.add("canUsedPoint");
			viewnameList.add("level");
			
			/*{field:'uid',title:'用户ID'},
            {field:'uname',title:'用户名'},
            {field:'realname',title:'真实姓名'},
            {field:'umobile',title:'电话'},
            {field:'uemail',title:'邮箱'},
            {field:'accountNo',title:'资金账号'},
            {field:'balance',title:'余额'},
            {field:'totalTenderAmount',title:'总投资额'},
            {field:'freeze',title:'冻结额'},
            {field:'canUseBalance',title:'可用余额'},
            {field:'produceCumulative',title:'累计积分'},
            {field:'canUsedPoint',title:'可用积分'},
            {field:'level',title:'会员等级',formatter:formatMemberLevel}*/
			
			form.setPageSize(100);
			form.setPageNum(1);
		
			PageVo searchListPage = userService.searchUserListPage("", form);
			searchListPage = userService.buildForExtraInfo(searchListPage);
			
			this.fillUser(searchListPage, viewnameList, sheet);
			int page = searchListPage.getPages();
			for(int i=2;i<=page;i++){
				form.setPageNum(i);
				searchListPage = userService.searchUserListPage("", form);
				searchListPage = userService.buildForExtraInfo(searchListPage);
				this.fillUser(searchListPage,viewnameList, sheet);
			}
			
			// 通过文件输出流生成Excel文件
			

			workBook.write(os);
			os.flush();
			os.close();
			//System.out.println("Excel 2003文件导出完成！导出文件路径：" + file.getPath());
		} catch (IOException e) {
			System.out.println("生成人员信息Excel发生IO 异常！" + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("文件导出发生异常！异常原因：" + e.getMessage());
			e.printStackTrace();
		}

	}
	
	private void fillUser(PageVo result,List<String> viewnameList, HSSFSheet sheet){
		int startrow =(result.getPageNum()-1)*result.getPageSize()+1;
		List<Map<String,Object>> rows = (List<Map<String,Object>>)result.getList();
		/*for(Map<String,Object> row:rows){
			Integer level = (Integer)row.get("level");
			String levelName = null;
			switch(level){
			//1-失败,2-无效,11-等待处理,21-提现处理中,31-提现成功
			case 0:
				levelName="普通";
				break;
			case 1:
				levelName="银牌";
				break;
			case 2:
				levelName="金牌";
				break;
			case 3:
				levelName="白金";
			
			default :levelName="未知";
				break;
				
			}
			row.put("level", levelName);
		}*/
		ExcelUtil.filldExcelByNameList(rows, viewnameList, sheet,startrow);
	}
}
